package com.baidu.infinity.ui.fragment.home.adapter

import android.graphics.Color
import android.os.Build
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.RequiresApi
import androidx.core.view.marginLeft
import androidx.core.view.setPadding
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.Recycler
import com.baidu.infinity.R
import com.baidu.infinity.databinding.LayoutColorItemBinding
import com.baidu.infinity.ui.fragment.home.shape.LayerManager

class ColorRecyclerAdapter: RecyclerView.Adapter<ColorRecyclerAdapter.MyViewHolder>() {
    private var colorList: List<Int> = emptyList()
    var currentColorListener: (color: Int) -> Unit = {}
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        val layoutInflater = LayoutInflater.from(parent.context)

        return MyViewHolder(LayoutColorItemBinding.inflate(layoutInflater))
    }

    @RequiresApi(Build.VERSION_CODES.VANILLA_ICE_CREAM)
    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        if(position >= 2){
            holder.bind(colorList[position - 2], listener = {
                LayerManager.instance.mColor = colorList[position - 2]
                currentColorListener(colorList[position - 2])
            })
        }else{
            if(position == 0){
                holder.bind(R.color.light_red, listener = {
                    val list = ArrayList<Int>(colorList)
                    list.add(LayerManager.instance.mColor)
                    setNewData(list)
                },R.drawable.add)

            }else{
                holder.bind(R.color.light_red, listener = {
                    val list = ArrayList<Int>(colorList)
                    list.removeLast()
                    setNewData(list)
                },R.drawable.menus)
            }
        }
    }

    override fun getItemCount(): Int {
         return colorList.size + 2
    }
    fun setNewData(colors: List<Int>){
        colorList = colors
        notifyDataSetChanged()
    }
    inner class MyViewHolder(var binding: LayoutColorItemBinding) : RecyclerView.ViewHolder(binding.root) {
        fun bind(color: Int,listener: (v:View)->Unit = {},src: Int = 0){
            binding.colorView.setImageResource(src)
            binding.colorView.setOnClickListener(listener)
            binding.colorView.setBackgroundColor(color)

        }
    }
}